package org.example.com.pattern.structure.flayweight

import java.awt.Canvas

/**
 * 结构型模式-享元模式
 * 享元模式通过共享多个对象所共有的相同状态，以便在有限的内存中载入更多对象。
 */


/**
 * 享元类，包含一个树的部分状态，这些成员变量保存的值对于特定树而言是唯一的。
 */
class TreeType(
    val name: String,
    val color: String,
    val texture: String
) {
    fun draw(canvas: Canvas, x: Int, y: Int) {

    }
}

/**
 * 享元工厂：决定是否复用已有享元对象或创建一个新的对象
 */
class TreeFactory {
    companion object {
        @JvmStatic
        private val treeTypes: MutableList<TreeType> = mutableListOf()
        fun getTreeType(name: String, color: String, texture: String): TreeType {
            var type = treeTypes.find { it.name == name && it.color == color && it.texture == texture }
            if (type == null) {
                type = TreeType(name, color, texture)
                treeTypes.add(type)
            }
            return type
        }
    }

}

/**
 * 情景对象，包含树状态的外在部分。
 */
class Tree(val x: Int, val y: Int, val type: TreeType) {
    fun draw(canvas: Canvas) {
        type.draw(canvas, x, y)
    }
}

class Forest {
    private val trees: MutableList<Tree> = mutableListOf()

    fun plantTree(x: Int, y: Int, name: String, color: String, texture: String) {
        val treeType = TreeFactory.getTreeType(name, color, texture)
        val tree = Tree(x, y, treeType)
        trees.add(tree)
    }

    fun draw(canvas: Canvas) {
        trees.forEach {
            it.draw(canvas)
        }
    }
}